<template>
  <div>
    <modal-view ref="modalViewRef" width="500px" :before-submit="beforeSubmit" @close="close">
      <el-form ref="formRef" label-width="80px" :model="formData" :rules="rules" label-position="left" size="small">
        <el-form-item label="编号">
          <el-input v-model="formData.Id" placeholder="自动生成" disabled></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <upload-img :doc-type="docType" v-model="formData._profile">
          </upload-img>
        </el-form-item>
        <el-form-item label="名称" prop="Name">
          <el-input v-model="formData.Name"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="formData.Sex">
            <el-radio-button v-for="item of SEX.array" :label="item.code">
              {{ item.name }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="formData.Phone"></el-input>
        </el-form-item>
      </el-form>
    </modal-view>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "MgrUserModalView",
})
</script>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import ModalView from "@/components/ModalView";
import { appAction } from "@/store/app";
import { docType, MgrUserDataClass } from "@/model/MgrUser";
import { request } from "@/utils/axios";
import { UploadImg } from "@/components/UploadFile";
import { SEX } from "@/config/constVar";

let emit = defineEmits<{
  (e: "close"): void;
  (e: "submit"): void
}>()

/**
 * 弹框
 */
let modalViewRef = ref();

/**
 * 表单
 */
let formRef = ref();

/**
 * 表单
 */
let formData = ref<MgrUserDataClass>(new MgrUserDataClass({}));


/**
 * 表单验证
 */
let rules = reactive({
  Name: [{ required: true, message: '当前项为必填项', trigger: 'blur' }],
})

/**
 * 页面展示
 */
function show(data?: any) {
  formData.value = new MgrUserDataClass(data || {});

  /**
   * 打开页面
   */
  modalViewRef.value.show();
}

/**
 *  保存前校验
 */
function beforeSubmit(): Promise<void> {
  return new Promise((resolve, reject) => {
    formRef.value.validate()
      .then(() => {

        let url = "";
        if (formData.value.Id) {
          //存在为修改
          url = "/" + docType + "/Update";
        } else {
          //不存在ID 为更新
          url = "/" + docType + "/Add";
        }

        //数据提交
        request(url, formData.value)
          .then(() => {
            ElMessage.success("表单数据保存成功");
            emit("submit");
            resolve();
          })
          .catch(() => {
            appAction.resetPageuuid();
            reject();
          })
      })
      .catch(reject)
  })
}

/**
 * 关闭页面
 */
function close() {
  emit("close")
}

/**
 * 导出
 */
defineExpose({
  show
})
/**
 * ====================
 *  页面初始化
 * ====================
 */


</script>

<style lang="less" scoped></style>